package com.ukao.pad.ui.stokin;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.AddClothingAdapter;
import com.ukao.pad.base.BaseFragment;
import com.ukao.pad.bean.AddClothingItem;
import com.ukao.pad.bean.ChooseClothingItem;
import com.ukao.pad.consts.Constant;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.eventbus.ChildFragmentEvent;
import com.ukao.pad.eventbus.UpdateChildChoose;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.retrofit.ApiCallback;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.widget.SearchStockinPopWindow;


import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;



/**
 * Created by ukaodev on 2017/5/24.
 */

@SuppressLint("ValidFragment")
public class ChooseClothingProjectFragment extends BaseFragment {


    @BindView(R.id.fragment_choose_clothing_clothing_type_radiogroup)
    RadioGroup mRadioGroup;
    @BindView(R.id.fragment_choose_clothing_search_edit)
    EditText mSearchEdit;
    @BindView(R.id.fragment_choose_clothing_search_btn)
    Button mSearchBtn;

    Unbinder unbinder;
    List<ChooseClothingItem> clothingItems = new ArrayList<>();
    @BindView(R.id.clothing_clothing_type)
    FrameLayout clothingClothingType;
    @BindView(R.id.search_layout)
    RelativeLayout searchLayout;
    private List<Integer> ids = new ArrayList<>();

    private String projectId = "";
    private ChooseClothingProjectChildFragment[] fragments;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private String proTypeId, currentParentId;
    public ChooseClothingProjectChildFragment showCurrenFragment;
    private SearchStockinPopWindow mSpinerPopWindow;
    private ArrayList<AddClothingItem> mSearchlist;
    private AddClothingAdapter mStockinAdapter;
    private List<AddClothingItem> allData;
    private String pricingMode;
    private String orderId;

    /*计价方式 1.门店 2.微信城市 3.智柜*/
    public static ChooseClothingProjectFragment getInstance( String pricingMode,String  orderId    ) {
        ChooseClothingProjectFragment fragment = new ChooseClothingProjectFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, pricingMode);
        args.putString(ARG_PARAM2,orderId);
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            pricingMode= getArguments().getString(ARG_PARAM1, "");
            orderId=getArguments().getString(ARG_PARAM2);
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_choose_addclothing_project, null);
        unbinder = ButterKnife.bind(this, view);
        isPrepared = true;
        initView();
        initListener();
        return view;
    }





    @Override
    protected void initListener() {
        super.initListener();
        mSearchEdit.setOnEditorActionListener(mOnEditorActionListener);
    }
    private TextView.OnEditorActionListener mOnEditorActionListener=new TextView.OnEditorActionListener(){
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftInput();
                return true;
            }
            return false;
        }
    };


    /**
     * 数据回显
     *
     * @param projectId       项目id
     * @param proTypeId       衣服tab id
     * @param currentParentId 衣物详情id
     */
    public void setDefaultMatchCheck(String projectId, String proTypeId, String currentParentId) {
        this.projectId = projectId;
        this.proTypeId = proTypeId;
        this.currentParentId = currentParentId;
        mHasLoadedOnce = false;
    }
    public void setProjectId(String projectId,String  proTypeId) {
        this.projectId = projectId;
        this.proTypeId = proTypeId;
        currentParentId="";
        mHasLoadedOnce = false;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if ( mHasLoadedOnce) return;
        getclothingData();

    }


    private void getclothingData() {
        clothingItems.clear();
        ids.clear();
        mRadioGroup.removeAllViews();
        clothingClothingType.removeAllViews();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("mercBusinessId", projectId);
        mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
        addSubscription(apiStores().productType(Constant.createParameter(mHashMap)),
                new ApiCallback<AddClothingItem>() {
                    @Override
                    public void onSuccess(AddClothingItem model) {
                        if (model.getHttpCode() == 200) {
                            mHasLoadedOnce = true;
                            fillData(model.getData());

                        } else {

                            T.show(model.getMsg());
                        }

                    }

                    @Override
                    public void onNoNewWork() {

                    }


                    @Override
                    public void onFinish() {

                    }
                });
    }


    private void fillData(List<AddClothingItem> data) {

        if (CheckUtils.isEmpty(data)) {
            return;
        }
        fragments = new ChooseClothingProjectChildFragment[data.size()];
        for (int i = 0; i < data.size(); i++) {
            AddClothingItem item = data.get(i);
            clothingItems.add(new ChooseClothingItem(item.getName(), item.getId(), ""));
            fragments[i] = !CheckUtils.isEmpty(proTypeId) && proTypeId.equals(item.getId()) ?
                    ChooseClothingProjectChildFragment.getInstance(item.getId(), projectId, currentParentId,pricingMode,orderId) : ChooseClothingProjectChildFragment.getInstance(item.getId(), projectId, "",pricingMode,orderId);

        }

        loadMultipleRootFragment(R.id.clothing_clothing_type, 0,
                fragments);
        initRaidoGroup();
    }

    /**
     * 初始化RaidoGroup
     */
    private void initRaidoGroup() {
        mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if(group.getCheckedRadioButtonId() == checkedId) {
                int i = 0;
                while (i < ids.size()) {
                    if (checkedId == ids.get(i)) {
                        showCurrenFragment = fragments[i];
                        showHideFragment(showCurrenFragment);

                    }
                    i++;
                }
            }
        });

        for (int i = 0; i < clothingItems.size(); i++) {
            RadioButton rb = (RadioButton) LayoutInflater.from(activity).inflate(R.layout.radiogroup_item, null);
            rb.setText(clothingItems.get(i).getName());

            /**
             * 目标设备为sdk 19，所以这里不考虑小于17
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                int id = View.generateViewId();
                rb.setId(id);
                ids.add(id);
            }
            mRadioGroup.addView(rb,ViewGroup.LayoutParams.WRAP_CONTENT  , ViewGroup.LayoutParams.MATCH_PARENT);
            if (!CheckUtils.isEmpty(proTypeId) && proTypeId.equals(clothingItems.get(i).getId())) {
                ((RadioButton) mRadioGroup.findViewById(ids.get(i))).setChecked(true);
            }

        }

        if (CheckUtils.isEmpty(proTypeId)&&!CheckUtils.isEmpty(ids))
            ((RadioButton) mRadioGroup.findViewById(ids.get(0))).setChecked(true);


    }

    @Override
    protected void initView() {
        mSearchlist = new ArrayList<>();

        mStockinAdapter = new AddClothingAdapter(_mActivity, mSearchlist, R.layout.activity_addclothing_search_list_item);
        mStockinAdapter.setOnItemClickListener(mSearchItemClickListener);
        mStockinAdapter.setIsSearchEnter(true);
//        mSpinerPopWindow = new SearchStockinPopWindow(activity);
//        mSpinerPopWindow.setAdatper(mStockinAdapter);
    }


    private OnItemClickListener mSearchItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            AddClothingItem mAddClothingItem = (AddClothingItem) o;
            String searchId = mAddClothingItem.getName();
            int j = 0;
            while (j < allData.size()) {
                AddClothingItem itemlist = allData.get(j);
                if (searchId.equals(itemlist.getName())) showCurrenFragment.updateItem(itemlist, j);

                j++;
            }
            mSpinerPopWindow.dismiss();
        }
    };

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UpdateChildChoose event) {

        String parentId = event.getPrentId();
        if (CheckUtils.isEmpty(clothingItems))return;
        for (int i = 0; i < clothingItems.size(); i++)
            if (clothingItems.get(i).getId().equals(parentId)) {
                showCurrenFragment = fragments[i];
                showHideFragment(showCurrenFragment);
                mRadioGroup.check(ids.get(i));
                ((ChooseClothingProjectChildFragment) fragments[i]).setSeektoPosition(event.getPosition());
                break;
            }
    }

    @Subscribe
    public void onEvent(ChildFragmentEvent event) {
        if (event.getMessage().equals(ChildFragmentEvent.Message.checked)) {
            String parentId = ((AddClothingItem) event.getData()).getId();
            if (CheckUtils.isEmpty(clothingItems))return;
            for (int i = 0; i < clothingItems.size(); i++) {
                if (clothingItems.get(i).getId().equals(parentId)) {

                    showCurrenFragment = fragments[i];
                    showHideFragment(showCurrenFragment);
                    mRadioGroup.check(ids.get(i));
                    break;
                }

            }

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.fragment_choose_clothing_search_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fragment_choose_clothing_search_btn:
                if (showCurrenFragment != null)
                allData = showCurrenFragment.getLoadData();
                String searchContext = getText(mSearchEdit);
                mSearchlist.clear();

                if (searchContext.isEmpty()) return;
                try {
                    for (AddClothingItem mitem : allData) {
                        if (mitem.getName().contains(searchContext)) {
                            mSearchlist.add(mitem);
                        } else if ( mitem.getFirstWord().toLowerCase().contains(searchContext.toLowerCase()) ){
                            mSearchlist.add(mitem);
                        }

                    }
                }catch (Exception  e){

                }
                mSpinerPopWindow.setData(mSearchlist);
                mSpinerPopWindow.setWidth(searchLayout.getWidth());
                mSpinerPopWindow.showAsDropDown(searchLayout);

                break;

        }
    }


}
